from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse,render,redirect

# class M1(MiddlewareMixin):
#     """中间件1"""
#     def process_request(self,request):
#         #如果方法中没有返回值（返回None）,继续向后走
#         #如果方法中没有返回值HttpResponse/render/redirect
#         print("M1,process_request")
#         return HttpResponse("无权访问")
#
#     def process_response(self,request,response):
#         print("M1,process_response")
#         return response
#
# class M2(MiddlewareMixin):
#     """中间件2"""
#     def process_request(self,request):
#         print("M2,process_request")
#
#     def process_response(self,request,response):
#         print("M2,process_response")
#         return response
class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
    # 排除掉那些不需要登录就能访问的页面
        if request.path_info in ['/login/','/image/code/']:#request.path_info获取当前用户请求的URL/Login
            return None
    # 如果方法中没有返回值（返回None）,继续向后走
    # 如果方法中没有返回值HttpResponse/render/redirect
    #1读取当前访问的用户的session信息，如果能读到那么，说明已经登录，就可以继续向后走
        info_dic=request.session.get('info')
        if info_dic:
            print("登录了")
            return
        #没有登录，重新登录
        return redirect('/login/')

    def process_response(self,request,response):
        return response